package com.doris.word.html;

import android.util.Log;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import fr.opensagres.poi.xwpf.converter.core.ImageManager;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;

public class WordToHtml {

    private static final String TAG = WordToHtml.class.getSimpleName();

    private static String cacheTempPath;

    public static void setCacheTempPath(String path) {
        cacheTempPath = path;
    }

    public static String toHtml(String path) {
        if (path.endsWith("doc")) {
            return docToHtml(path);
        } else {
            return docxToHtml(path);
        }
    }

    private static String docxToHtml(String path) {
        try {
            FileInputStream fis = new FileInputStream(path);
            XWPFDocument document = new XWPFDocument(fis);
            XHTMLOptions options = XHTMLOptions.create();
            //忽略未用到的样式 默认true
            options.setIgnoreStylesIfUnused(false);
            //将样式都写为内联样式，而不是写到style标签中 默认false
            options.setFragment(true);
            //设置html 图片储存位置.需要传服务器的,可以继承ImageManager,自己处理逻辑.
            options.setImageManager(new ImageManager(new File(cacheTempPath), "img"));
            File file = new File(cacheTempPath, path.substring(path.lastIndexOf("/") + 1,
                    path.lastIndexOf(".")) + ".html");
            FileOutputStream fos = new FileOutputStream(file);
            XHTMLConverter.getInstance().convert(document, fos, options);
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String docToHtml(String path) {
        try {
            InputStream input = new FileInputStream(path);
            HWPFDocument wordDocument = new HWPFDocument(input);
            Document newDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

            WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(newDocument);
            wordToHtmlConverter.setPicturesManager((content, pictureType, suggestedName, widthInches, heightInches) -> suggestedName);
            wordToHtmlConverter.processDocument(wordDocument);
            List<Picture> pics = wordDocument.getPicturesTable().getAllPictures();
            if (pics != null) {
                for (Picture pic : pics) {
                    try {
                        pic.writeImageContent(new FileOutputStream(
                                cacheTempPath + File.separator + pic.suggestFullFileName()));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
            Document document = wordToHtmlConverter.getDocument();
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            DOMSource domSource = new DOMSource(document);
            StreamResult streamResult = new StreamResult(outStream);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer serializer = tf.newTransformer();
            serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty(OutputKeys.METHOD, "html");
            serializer.transform(domSource, streamResult);
            outStream.close();
            String content = outStream.toString();
            content = content.replace("<img src=\"", "<img src=\"" + cacheTempPath + "/");

            File file = new File(cacheTempPath,
                    path.substring(path.lastIndexOf("/") + 1,
                            path.lastIndexOf(".")) + ".html");
            createFile(file, content);
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            if (Objects.requireNonNull(e.getMessage()).contains("OOXML")){
                return docxToHtml(path);
            }
        }
        return "";
    }

    private static void createFile(File file, String content) {
        if (file.exists()) {
            Log.d(TAG, "createFile: exists-delete=" + file.delete());
        }
        try {
            Log.d(TAG, "createFile: create=" + file.createNewFile());
            FileOutputStream outStream = new FileOutputStream(file);
            outStream.write(content.getBytes());
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
